package topic

import (
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/common/request"
	"gitcode.com/G-YT/iHealth25/server/model/topic"
	topicReq "gitcode.com/G-YT/iHealth25/server/model/topic/request"
	topicRes "gitcode.com/G-YT/iHealth25/server/model/topic/response"
)

type TopicService struct {
}

// CreateTopic 创建Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) CreateTopic(toPic *topic.Topic) (err error) {
	err = global.GVA_DB.Create(toPic).Error
	return err
}

// DeleteTopic 删除Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) DeleteTopic(toPic topic.Topic) (err error) {
	err = global.GVA_DB.Delete(&toPic).Error
	return err
}

// DeleteTopicByIds 批量删除Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) DeleteTopicByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]topic.Topic{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateTopic 更新Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) UpdateTopic(toPic topic.Topic) (err error) {
	err = global.GVA_DB.Save(&toPic).Error
	return err
}

// GetTopic 根据id获取Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) GetTopic(id uint) (toPic topic.Topic, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&toPic).Error
	return
}

// GetTopicInfoList 分页获取Topic记录
// Author [piexlmax](https://github.com/piexlmax)
func (toPicService *TopicService) GetTopicInfoList(info topicReq.TopicSearch) (list []topic.Topic, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&topic.Topic{})
	var toPics []topic.Topic
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", info.Name)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["sort"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	err = db.Limit(limit).Offset(offset).Find(&toPics).Error
	return toPics, total, err
}

// GetTopicList 获取话题记录
// Author [g-qs](https://github.com/g-qs)
func (toPicService *TopicService) GetTopicList() (list []topicRes.TopTopic, err error) {
	var topTopic []topicRes.TopTopic
	err = global.GVA_DB.Model(&topicRes.TopTopic{}).Preload("Topic").Where("sys_dictionary_id = ?", 7).Find(&topTopic).Error
	return topTopic, err
}
